package standalone.utils;

import java.io.File;
import java.io.FileFilter;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.ui.velocity.VelocityEngineUtils;


public class CreateProcrunCommands {
	public static void main(String[] args) {
		try {
			
			File f = new File("src/main/resources/META-INF/log4j.xml");
			if (f.exists()) {
			} else {
				f = new File("../META-INF/log4j.xml");
			}
			System.setProperty("log4j.configuration", "file:/"+f.getAbsolutePath().replace("\\", "/"));			
			System.setProperty("log4j.debug","");
			System.setProperty("user.dir",f.getParentFile().getParentFile().getAbsolutePath());

			
			String libDir = args[0];
			String outputDir = args[1];
			String tmpltDir = args[2];

			ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/utilitiesContext.xml");
			VelocityEngine velocityEngine = (VelocityEngine)context.getBean("velocityEngine");
			Map<String, Object> tmpltData = new HashMap<String, Object>();

			f = new File(libDir);
			File[] files = f.listFiles(new FileFilter() {
				@Override
				public boolean accept(File pathname) {
					return pathname.getName().endsWith("jar");
				}
			});
			String mailerClasspath = "%JAVA_HOME%/jre/lib/rt.jar;";
			for (File myJar : files) {
				mailerClasspath = mailerClasspath + ( "%_LIBDIR%/"+myJar.getName()+";");
			}
			System.out.println("have classpath: " + mailerClasspath);
			tmpltData.put("mailerClasspath", mailerClasspath);
			
			f = new File(tmpltDir);
			files = f.listFiles(new FileFilter() {
				@Override
				public boolean accept(File pathname) {
					return pathname.getName().endsWith("tmpl");
				}
			});
			for (File tmplt : files) {
				String outputName = tmplt.getName().replace(".tmpl", "");
				System.out.println("working on : " + outputName);
				FileWriter fw = new FileWriter(outputDir + "/" + outputName);
				VelocityEngineUtils.mergeTemplate(velocityEngine, "velocity/procrun/" + tmplt.getName() , tmpltData, fw);
				fw.flush();
				fw.close();				
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
